import 'package:flutter/cupertino.dart';
import 'package:flutter_chat_ui/https/http_response.dart';
import 'package:flutter_chat_ui/https/request.dart';
import 'package:flutter_chat_ui/models/chat_message_model.dart';
import 'package:flutter_chat_ui/models/chat_room_info_mode.dart';
import 'package:flutter_chat_ui/models/chat_session_model.dart';
import 'package:flutter_chat_ui/models/chat_suggested_question_model.dart';
import 'package:flutter_chat_ui/models/chat_opening_remarks_model.dart';
import 'package:flutter_chat_ui/utils/utils.dart';

/// 响应模式
enum ResponseMode {
  streaming('streaming'),
  blocking('blocking');

  final String value;

  const ResponseMode(this.value);
}

///
/// 聊天请求
///
mixin ChatReuqestMixin {
  ///
  /// 获取应用基本信息。
  ///
  void requestGetAppInfo({
    Success<ChatRoomInfoData?>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    XHttpRequest.request(
      Method.get,
      '/info',
      success: (data) {
        ChatRoomInfoData? resData = ChatRoomInfoData.fromJson(data);
        success?.call(resData);
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }

  ///
  /// 获取应用参数。
  ///
  /// 进入页面一开始，获取推荐问题、功能开关、输入参数名称、类型及默认值等使用。
  ///
  void requestGetAppParams({
    Success<OpeningRemarksData?>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    XHttpRequest.request(
      Method.get,
      '/parameters',
      success: (data) {
        OpeningRemarksData? resData;
        if (data != null) {
          resData = OpeningRemarksData.fromJson(data);
        }
        success?.call(resData);
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }

  ///
  /// 获取当前机器人answer下的下一轮建议问题列表。
  ///
  void reuqestGetNextSuggestedQuestions(
    String mesaageId, {
    required String userId,
    Success<List<String>>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    XHttpRequest.request(
      Method.get,
      '/messages/$mesaageId/suggested?user=$userId',
      success: (data) {
        List<String> questions = [];

        if (data != null) {
          final value = ChatSuggestedQuestionsAfterAnswerData.fromJson(data);
          questions = value.data;
        }
        success?.call(questions);
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }

  ///
  /// 请求机器人响应消息。
  ///
  /// query: 消息内容
  ///
  /// conversation_id: 会话 ID，需要基于之前的聊天记录继续对话，必须传之前消息的 conversation_id
  ///
  void requestGetRobotResponse(
    String query, {
    required String userId,
    String conversationId = '',
    Map<String, String> inputs = const {},
    bool isStream = true,
    Map<String, String>? header = const {'Accept': 'text/event-stream'},
    Success<dynamic>? success,
    Success<Stream>? streamSuccess,
    Fail? fail,
    VoidCallback? complete,
  }) {
    Map<String, dynamic> params = {
      'query': query,
      "user": userId,
      'conversation_id': conversationId,
      "response_mode":
          isStream ? ResponseMode.streaming.value : ResponseMode.blocking.value,
      "inputs": inputs,
      "files": [],
    };
    XHttpRequest.request(
      Method.post,
      '/chat-messages',
      params: params,
      header: header,
      isStream: isStream,
      success: (data) {
        if (isStream) {
          /// 处理流式响应
          streamSuccess?.call(data);
        } else {
          success?.call(data);
        }
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }

  ///
  /// 停止当前会话。
  ///
  /// success: 成功回调: "result" -> "success"
  ///
  void requestStopRobotResponse(
    String taskId, {
    required String userId,
    Success<bool>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    Map<String, dynamic> params = {
      "user": userId,
    };
    XHttpRequest.request(
      Method.post,
      '/chat-messages/$taskId/stop',
      params: params,
      success: (data) {
        success?.call(data['result'] == 'success');
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }

  ///
  /// 获取会话记录。
  ///
  /// user_id: 用户 ID
  ///
  /// last_id:（选填）当前页最后面一条记录的 ID，默认 null
  ///
  /// limit:（选填）一次请求返回多少条记录，默认 20 条，最大 100 条，最小 1 条。
  ///
  void requestGetChatList({
    required String userId,
    String? lastId,
    int limit = 20,
    Success<ChatSessionListData?>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    XHttpRequest.request(
      Method.get,
      "/conversations?user=$userId&last_id=${lastId ?? ''}&limit=$limit",
      success: (data) {
        ChatSessionListData? resData;
        if (data != null) {
          resData = ChatSessionListData.fromJson(data);
        }
        success?.call(resData);
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }

  ///
  /// 获取会话历史消息。
  ///
  void requestGetChatHistory({
    String userId = '',
    String conversationId = '',
    int limit = 5,
    Success<List<ChatMessageData>>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    XHttpRequest.request(
      Method.get,
      '/messages?user=$userId&conversation_id=$conversationId&limit=$limit',
      success: (json) {
        List<ChatMessageData> chatMessages = [];
        // 处理会话历史数据
        if (json != null) {
          // 遍历消息列表，交替添加用户和机器人消息
          final historyList = json['data'] as List<dynamic>;
          for (var i = 0; i < historyList.length; i++) {
            // 用户消息
            final masterMessage = ChatMessageData(
              event: MessageEventType.master.event,
              messageId: Utils.getUniqueId(),
              query: historyList[i]['query'],
              createdAt: historyList[i]['created_at'],
            );
            // 机器人消息
            final robotMessage = ChatMessageData(
              event: MessageEventType.robot.event,
              messageId: Utils.getUniqueId(),
              createdAt: historyList[i]['created_at'],
              robotResponseText: historyList[i]['answer'],
            );
            chatMessages.addAll([masterMessage, robotMessage]);
          }
        }
        success?.call(chatMessages);
      },
      fail: (code, msg) {},
      complete: complete,
    );
  }

  ///
  /// 某个会话重新命名
  ///
  void requestRenameChatSession(
    String conversationId, {
    required String userId,
    Success<ChatSessionRenameData>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    Map<String, dynamic> params = {
      "user": userId,
      "name": "",
      "auto_generate": true,
    };

    XHttpRequest.request(
      Method.post,
      '/conversations/$conversationId/name',
      params: params,
      success: (data) {
        if (data != null) {
          ChatSessionRenameData? resData = ChatSessionRenameData.fromJson(data);
          success?.call(resData);
        }
      },
      fail: (code, msg) {},
      complete: complete,
    );
  }

  ///
  /// 删除某一个会话。
  ///
  /// conversationId: 会话 ID
  ///
  /// userId: 用户 ID
  ///
  /// success: 成功回调: 204 No Content
  ///
  void requestDeleteChatSession(
    String conversationId, {
    required String userId,
    Success<dynamic>? success,
    Fail? fail,
    VoidCallback? complete,
  }) {
    Map<String, dynamic> params = {
      "user": userId,
    };

    XHttpRequest.request(
      Method.delete,
      '/conversations/$conversationId',
      params: params,
      success: (data) {
        success?.call(data);
      },
      fail: (code, msg) {
        fail?.call(code, msg);
      },
      complete: complete,
    );
  }
}
